<template>
  <div style="">
    <!--      登录页面    -->
    <div style="height: 100vh; overflow: hidden; position: relative;" :style="background">
      <!--      logo位置    -->
      <div style="display: flex; justify-content: center; text-align: center; align-items: center; margin-top: 10px;
        font-size: 1.2em; color: white; font-weight: normal; text-shadow: 2px 2px 4px rgba(0,0,0,1)">
        <div>
          <img src="../../assets/image/common/logo.png" alt="logo" style="width:40px; filter: brightness(1.5); height: auto; margin-top: 5px;">
        </div>
        <div>
          <span style="margin-left: 6px" class="title">金玥智阅</span>
        </div>
      </div>
      

      <!--             登录框          -->
      <div class="login-box" @mouseover="!isToggleActive ? showLoginBox() : null"
           @mouseleave="!isToggleActive ? hideLoginBox() : null" :class="{ expanded: isLoginBoxExpanded }">
        <div>
          <!-- 单选按钮，用于选择用户或管理员登录 -->
          <el-radio-group v-model="role" style="margin: 0 0; text-align: center;" @change="getPrimaryMessage()">
            <el-radio label="user" style="color: white">读者登录</el-radio>
            <el-radio label="admin" style="color: white; margin-left: 40px;">管理员登录</el-radio>
          </el-radio-group>
          <!-- 收缩/展开按钮 -->
          <div style="position: absolute; top: 20px; right: 5px; cursor: pointer; color: aqua; font-size: 15px;" @click="toggleLoginBox()">
            <span :class="['rotate-icon', { rotate: !isToggleActive }]">
              '▼'  <!-- 美观的箭头 -->
            </span>

          </div>
        </div>

        <!-- 当登录框展开时，显示表单 -->
        <el-form v-if="isLoginBoxExpanded" :model=" role === 'admin' ? admin : user"
                 ref="loginForm" :rules="rules" style="margin-top: 30px">
          <el-form-item prop="account" v-if="role === 'admin'">
            <el-input placeholder="请输入账号"  prefix-icon="el-icon-user" size="medium"
                      v-model="admin.account "></el-input>
          </el-form-item>
          <el-form-item prop="account" v-if="role === 'user'">
            <el-input placeholder="请输入账号"  prefix-icon="el-icon-user" size="medium"
                      v-model="user.account"></el-input>
          </el-form-item>
          <el-form-item prop="password" v-if="role === 'admin'">
            <el-input placeholder="请输入密码"  show-password prefix-icon="el-icon-lock" size="medium"
                      v-model="admin.password"></el-input>
          </el-form-item>
          <el-form-item prop="password" v-if="role === 'user'">
            <el-input placeholder="请输入密码"  show-password prefix-icon="el-icon-lock" size="medium"
                      v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item prop="captcha" style="display: flex; align-items: center;">
            <div style="flex: 1; display: flex; align-items: center">
              <el-input placeholder="请输入验证码"   prefix-icon="el-icon-lock" size="medium" v-if="role === 'admin'"
                        v-model="admin.captcha" style="width: 130px;">
              </el-input>
              <el-input placeholder="请输入验证码"   prefix-icon="el-icon-s-check" size="medium" v-if="role === 'user'"
                        v-model="user.captcha" style="width: 130px;">
              </el-input>
              <img :src="captchaImage" alt="图形验证码" @click="setCaptcha"  style="width: 100px; height: 40px; margin-left: 20px"/>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="margin-top: -5px;">
              <el-checkbox v-model="remember" class="rememberMe" style="color: white">记住我</el-checkbox>
              <span @click="$router.push('/forgetPassword')" class="password-text" v-if="role === 'user'" >忘记密码？</span>
            </div>
            <el-button  size="medium" type="primary" @click="login" class="custom-login-button">登录</el-button>
            <div v-if="role === 'user'" style="color: white">
              <span>还没有账号?去</span><span class="register-text" @click="$router.push('/register')">注册</span>
            </div>

          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import adminRequest from "@/utils/adminRequest";
import userRequest from "@/utils/userRequest";
// 引入Base64进行密码加密处理
const Base64 = require("js-base64").Base64;
import Cookies from "js-cookie";
import {getVerifyCode} from "@/utils/setCaptcha";

const login_background = require("@/assets/image/login/login-background.jpg");

export default {
  name: 'Login',
  data() {
    return {
      role: localStorage.getItem('role'), // 当前角色，默认是上一次登陆的角色
      remember: false, // 是否记住用户名和密码
      isLoginBoxExpanded: false, // 登录框初始状态为未展开
      isArrowDown: false,  // 控制箭头方向
      isToggleActive: false,  // 是否箭头开关激活
      admin: {
        account: '',
        password: '',
        captcha: '', // 管理员输入验证码
        captchaKey: '',
      },
      captchaImage: '',
      user: {
        account: '',
        password: '',
        captcha: '', // 用户输入验证码
        captchaKey: '',
      },
      rules: {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 10, message: '长度为1-10个字符', trigger: 'blur' }],
        password: [{required: true, message: '请输入密码', trigger: 'blur'},
          {pattern: /^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,16}$/,
            message: '密码必须为8-16位，且包含大小写字母', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' },]
      },
      background: {
        backgroundImage: "url(" + login_background + ")",
        backgroundSize: "cover",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
      },
    }
  },

  created() {
    this.setCaptcha();
    this.getPrimaryMessage();
  },

  methods: {
    showLoginBox() {  // 鼠标悬停时显示登录框
      this.isLoginBoxExpanded = true;   // 展开登录框
    },

    // 获取验证码并显示
    async setCaptcha() {
      const res = await getVerifyCode();
      // 获取并显示验证码图片
      this.captchaImage = URL.createObjectURL(new Blob([res.data], { type: 'image/png' }));
    },

    hideLoginBox() {    // 鼠标离开时隐藏登录框
      if (this.isLoginBoxExpanded) {
        // 只有当鼠标离开登录框时才收缩
        this.isLoginBoxExpanded = false;
      }
    },
    // 获取之前登录信息
    getPrimaryMessage() {
      if(this.role) {
        if(this.role === 'user') {   // 记住用户账号和密码的设置
          let account = localStorage.getItem('account')
          if(account) { // 如果存储的用户存在，将值赋给登录表单
            this.user.account = localStorage.getItem('account')
            // 解密密码
            this.user.password = Base64.decode(localStorage.getItem('password'))
            this.remember = true
          }
        }
        else if(this.role === 'admin') {     // 记住管理员用户名和密码的设置
          let account = localStorage.getItem('account')
          if (account) { // 如果存储的管理员存在，将值赋给登录表单
            this.admin.account = localStorage.getItem('account')
            // 解密密码
            this.admin.password = Base64.decode(localStorage.getItem('password'))
            this.remember = true
          }
        }
      }
    },
    // 切换登录框的展开状态
    toggleLoginBox() {
      if(!this.isToggleActive) {
        this.isToggleActive = true;
        this.isLoginBoxExpanded = true;
      }
      else if(this.isToggleActive) {
        this.isToggleActive = false;
      }
    },

    // 登录逻辑
    login() {
      this.$refs['loginForm'].validate(async (valid) => {
        if (valid) {
          if (this.role === 'admin') {    // 管理员登录
            this.admin.captchaKey = Cookies.get('captcha-key');
            adminRequest.post('/account/login',  this.admin ).then(res => {
              if (res.code === 200) {       // 登录成功
                this.$admin.set(res.data)
                // 登录成功后跳转到主页面
                this.$router.push('/layout').then(() => {
                  this.$nextTick(() => {
                    this.$message.success(res.data.account + ", 欢迎回来!");
                  });
                });

                if (this.remember) {       // 记住密码,保留用户名和密码
                  let password = Base64.encode(this.admin.password); // base加密
                  localStorage.setItem('account', this.admin.account);
                  localStorage.setItem('password', password);
                } else {
                  localStorage.removeItem('account');
                  localStorage.removeItem('password');
                }
                localStorage.setItem('role', this.role);  // 保留当前登陆的用户类型

              } else {
                this.setCaptcha(); // 更换验证码
              }
            })
          }
          else if (this.role === 'user') {     // 用户登录
            this.user.captchaKey = Cookies.get('captcha-key');
            console.info(this.user.captchaKey)
            userRequest.post('/account/login', this.user ).then(res => {
              if (res.code === 200) {       // 登录成功
                this.$user.set(res.data)
                if (this.remember) {       // 记住密码,保留用户名和密码
                  let password = Base64.encode(this.user.password); // base加密
                  localStorage.setItem('account', this.user.account);
                  localStorage.setItem('password', password);
                } else {
                  localStorage.removeItem('account');
                  localStorage.removeItem('password');
                }
                localStorage.setItem('role', this.role);  // 保留当前登陆的用户类型
                // 登录成功后跳转到主页面
                this.$router.push('/user/home').then(() => {
                  this.$nextTick(() => {
                    this.$message.success(res.data.username + ", 欢迎回来!");
                  });
                });
              } else {
                this.setCaptcha(); // 更换验证码
              }
            })
          }
        }
      })
    },

  },
};
</script>

<style scoped>
.login-box {
  opacity: 0.6; /* 设置登录框透明度 */
  width: 350px; /* 登录框宽度 */
  height: 60px; /* 默认高度，只有单选按钮部分可见 */
  background-color: #545c64; /* 背景颜色 */
  border-radius: 10px; /* 圆角 */
  margin: 140px 0 auto 150px; /* 外边距 */
  padding: 20px 50px; /* 内边距 */
  position: fixed; /* 固定定位 */
  transition: height 1.8s ease; /* 收缩动画效果 */
  overflow: hidden; /* 隐藏超出部分 */
}

.login-box.expanded {
  transition: height 1s ease-in-out;
  height: 360px; /* 展开时的高度 */
}

.rotate-icon {
  display: inline-block; /* 图标为行内块元素 */
  transition: transform 1s ease; /* 展开旋转动画 */
}

.rotate-icon.rotate {
  transform: rotate(90deg); /* 旋转效果 */
}

/* 为单选按钮设置样式 */
.el-radio {
  display: inline-block; /* 设置为行内块元素 */
  margin: 0 10px; /* 左右外边距 */
}



/deep/ .el-radio__input.is-checked + .el-radio__label {
  color: aqua; /* 设置选中状态的字体颜色 */
}
/deep/ .rememberMe .el-checkbox__input.is-checked + .el-checkbox__label {
  color: aqua; /* 选中后字体颜色 */
}

.register-text {
  color: #d9d9d9; /* 初始颜色 */
  cursor: pointer; /* 鼠标变成手指 */
  font-size: medium;
}
.register-text:hover {
  color: aqua; /* 鼠标悬停时的颜色 */
}
.password-text {
  color: #d9d9d9; /* 初始颜色 */
  cursor: pointer; /* 鼠标变成手指 */
  font-size: medium;
  margin-left: 100px;
}
.password-text:hover {
  color: aqua; /* 鼠标悬停时的颜色 */
}
.custom-login-button {
  background-color: #545c64;
  width: 100%;
  color: white;
  font-weight: bolder;
  font-size: large;
}
.custom-login-button:hover {
  background-color: #6b737a; /* 设置鼠标悬停时的背景色 */
  color: aqua; /* 设置悬停时的文字颜色 */
}


</style>
